package com.airbat.prize.modules.system.controller.dict;

import com.airbat.prize.common.pojo.CommonResult;
import com.airbat.prize.common.pojo.PageResult;
import com.airbat.prize.excel.core.util.ExcelUtils;
import com.airbat.prize.modules.system.controller.dict.vo.data.*;
import com.airbat.prize.modules.system.convert.dict.SysDictDataConvert;
import com.airbat.prize.modules.system.dal.dataobject.dict.SysDictDataDO;
import com.airbat.prize.modules.system.service.dict.SysDictDataService;
import com.airbat.prize.operatelog.core.annotations.OperateLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.airbat.prize.common.pojo.CommonResult.success;
import static com.airbat.prize.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "字典数据")
@RestController
@RequestMapping("/system/dict-data")
@Validated
public class SysDictDataController {

    @Resource
    private SysDictDataService dictDataService;

    @PostMapping("/create")
    @ApiOperation("新增字典数据")
    @PreAuthorize("@ss.hasPermission('system:dict:create')")
    public CommonResult<Long> createDictData(@Valid @RequestBody SysDictDataCreateReqVO reqVO) {
        Long dictDataId = dictDataService.createDictData(reqVO);
        return success(dictDataId);
    }

    @PutMapping("update")
    @ApiOperation("修改字典数据")
    @PreAuthorize("@ss.hasPermission('system:dict:update')")
    public CommonResult<Boolean> updateDictData(@Valid @RequestBody SysDictDataUpdateReqVO reqVO) {
        dictDataService.updateDictData(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除字典数据")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:dict:delete')")
    public CommonResult<Boolean> deleteDictData(Long id) {
        dictDataService.deleteDictData(id);
        return success(true);
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获得全部字典数据列表", notes = "一般用于管理后台缓存字典数据在本地")
    // 无需添加权限认证，因为前端全局都需要
    public CommonResult<List<SysDictDataSimpleRespVO>> getSimpleDictDatas() {
        List<SysDictDataDO> list = dictDataService.getDictDatas();
        List<SysDictDataSimpleRespVO> sysDictDataSimpleRespVOS = new ArrayList<>(list.size());
        list.forEach(dictData -> {
            SysDictDataSimpleRespVO sysDictDataSimpleRespVO = SysDictDataConvert.INSTANCE.convertToSimple(dictData);
            if (dictData.getParentId() != null)
                sysDictDataSimpleRespVO.setParentDictData(SysDictDataConvert.INSTANCE.convertToSimple(dictDataService.getDictData(dictData.getParentId())));
            sysDictDataSimpleRespVOS.add(sysDictDataSimpleRespVO);
        });
        return success(sysDictDataSimpleRespVOS);
    }

    @GetMapping("/type/{dictType}")
    @ApiOperation(value = "获得字典数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictType", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "remark", dataTypeClass = String.class)
    })
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    public CommonResult<List<SysDictDataDO>> getDictDatas(@PathVariable("dictType") List<String> dictType, @RequestParam(value = "remark", required = false) String remark) {
        List<SysDictDataDO> list = new ArrayList<>();
        for (String dt : dictType) {
            List<SysDictDataDO> listTemp = dictDataService.getParentDictDatas(dt);
            if (StringUtils.isNotEmpty(remark)) {
                listTemp = listTemp.stream().filter(tr -> StringUtils.isNotEmpty(tr.getRemark()) && tr.getRemark().equals(remark)).collect(Collectors.toList());
                list.addAll(listTemp);
            } else {
                list.addAll(listTemp);
            }
        }
        return success(list);
    }

    @GetMapping("/children")
    @ApiOperation(value = "获得字典子列表")
    @ApiImplicitParam(name = "id", required = true, dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    public CommonResult<List<SysDictDataDO>> getChildrenDatas(@RequestParam Long id) {
        List<SysDictDataDO> list = dictDataService.getChildrenDictDatas(id);
        return success(list);
    }


    @GetMapping("/page")
    @ApiOperation("/获得字典类型的分页列表")
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    public CommonResult<PageResult<SysDictDataRespVO>> getDictTypePage(@Valid SysDictDataPageReqVO reqVO) {
        PageResult<SysDictDataDO> sysDictDataDOPageResult = dictDataService.getDictDataPage(reqVO);
        List<SysDictDataRespVO> dictDataRespVOS = new ArrayList<>(sysDictDataDOPageResult.getList().size());
        sysDictDataDOPageResult.getList().forEach(dictData -> {
            SysDictDataRespVO sysDictDataRespVO = SysDictDataConvert.INSTANCE.convert(dictData);
            if (sysDictDataRespVO.getParentId() != null)
                sysDictDataRespVO.setParentDictData(dictDataService.getDictData(dictData.getParentId()));
            dictDataRespVOS.add(sysDictDataRespVO);
        });
        return success(new PageResult<>(dictDataRespVOS, sysDictDataDOPageResult.getTotal()));
    }

    @GetMapping(value = "/get")
    @ApiOperation("/查询字典数据详细")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:dict:query')")
    public CommonResult<SysDictDataRespVO> getDictData(@RequestParam("id") Long id) {
        SysDictDataDO sysDictDataDO = dictDataService.getDictData(id);
        SysDictDataRespVO sysDictDataRespVO = SysDictDataConvert.INSTANCE.convert(sysDictDataDO);
        if (sysDictDataDO.getParentId() != null)
            sysDictDataRespVO.setParentDictData(dictDataService.getDictData(sysDictDataDO.getParentId()));
        return success(sysDictDataRespVO);
    }

    @GetMapping("/export")
    @ApiOperation("导出字典数据")
    @PreAuthorize("@ss.hasPermission('system:dict:export')")
    @OperateLog(type = EXPORT)
    public void export(HttpServletResponse response, @Valid SysDictDataExportReqVO reqVO) throws IOException {
        List<SysDictDataDO> list = dictDataService.getDictDatas(reqVO);
        List<SysDictDataExcelVO> data = SysDictDataConvert.INSTANCE.convertList02(list);
        // 输出
        ExcelUtils.write(response, "字典数据.xls", "数据列表", SysDictDataExcelVO.class, data);
    }

}
